package com.outfood.task;

import com.alibaba.fastjson.JSON;
import com.outfood.common.eleme.Result;
import com.outfood.common.order.Details;
import com.outfood.config.PythonServerConfig;
import com.outfood.domain.Order;
import com.outfood.domain.Rule;
import com.outfood.domain.Store;
import com.outfood.service.IOrderService;
import com.outfood.service.IRuleService;
import com.outfood.service.IStoreService;
import com.outfood.service.impl.ElmeOperateServiceImpl;
import com.outfood.service.impl.MeiTuanOperateServiceImpl;
import com.outfood.service.impl.SeleniumServiceImpl;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.DateUtils;
import com.rys.common.utils.Search;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.task
 * @Date 2024-03-25 17:08
 * @Version 1.0
 */
@Component
@Log4j2
public class ScanElemeOrderTask {

    @Resource
    IStoreService storeService;
    @Resource
    ElmeOperateServiceImpl elmeOperateService;
    @Resource
    IOrderService orderService;
    @Resource
    IRuleService ruleService;



    @SneakyThrows
 //   @Scheduled(cron = "0 */3 * * * ?")
    public void scan(){
        Thread.sleep(new Random().nextInt(1000));
        long start  = new Date().getTime();
        log.info("--------------------------------------------开始获取饿了么待出餐订单------------------------------------------------------------");//
        List<Store> storeList = storeService.getList(new Search().add("storeStatus", SearchTypeEnum.EqualTo,"1").add("platform","ELEME").add("onlineStatus",SearchTypeEnum.EqualTo,"ONLINE"));
        storeList.forEach(store -> {
            try {
                Thread.sleep(new Random().nextInt(1000));
                if("FALSE".equals(store.getAutoOut())){
                    log.warn("{}没有开启自动出餐",store.getStoreName());
                    return;
                }
                ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
                query.setShopId(store.getRegionId());
                query.setKsid(store.getCookie());
                query.setStoreId(store.getId());
                List<Result> orderList = elmeOperateService.getOrderList(query);
                if(CollectionUtils.isEmpty(orderList)){
                    return ;
                }

                orderList.forEach(orderItem ->{
                    saveOrder(store, orderItem);

                });
            } catch (Exception e) {
                log.error("获取订单失败",e);
            }

        });
        long end  = new Date().getTime();
        log.info("------------------------------------------获取饿了么待出餐订单结束共耗时{}ms------------------------------------------------------------",end-start);

    }

    private void saveOrder(Store store, Result orderItem) {
        List<Store> ss = storeService.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, orderItem.getShopId()));
        if(CollectionUtils.isEmpty(ss)){
            return;
        }
        if("FALSE".equals(ss.get(0).getAutoOut())){
            log.warn("{}子门店没有开启自动出餐", store.getStoreName());
            return;
        }
        Rule rule = ruleService.getList(new Search().add("storeId", SearchTypeEnum.EqualTo, ss.get(0).getId())).get(0);
        Order order = new Order();
        order.setOrderTime(orderItem.getActiveTime());
        order.setTheoryOutTime(new Date(order.getOrderTime().getTime()+1000*60*rule.getTime()));
        //order.setBuyerName(orderItem.get);
        String foodName = orderItem.getFoodInfo().getGroups().get(0).getItems().stream().map(item -> item.getName()).collect(Collectors.joining(","));
        order.setFoodName(foodName);

//                    order.setIncome(orderItem.getDetail().getChargeInfo().getFixedSettlementInfo().getSettleAmount()+"");
//                    order.setPoiId(orderItem.getCommonInfoObj().getWmPoiId()+"");
//                    order.setOrderNo(orderItem.getCommonInfoObj().getWm_poi_order_dayseq()+"");
//                    order.setBuyerName(orderItem.getDetail().getUserInfo().getRecipientName());
        order.setOutStatus("READY");
        order.setStoreId(store.getId());
        order.setOrderNo(orderItem.getHeader().getDaySn());
        order.setOrderSource("ELEME");
        order.setOutTradeNo(orderItem.getId());
        order.setPoiId(orderItem.getShopId()+"");
//                    order.setRider(orderItem.getDetail().getLogisticsInfo().getTitle());
//                    order.setOutTradeNo(orderItem.getCommonInfoObj().getWm_order_id_view()+"");
//                    order.setInfo(JSON.toJSONString(orderItem));
        List<Order> result = orderService.getList(new Search().add("outTradeNo", SearchTypeEnum.EqualTo, orderItem.getId()));
        if(CollectionUtils.isEmpty(result)){
            orderService.add(order,"task");
        }
    }

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    ThreadPoolExecutor threadPoolExecutor;
    @Resource
    MeiTuanOperateServiceImpl meiTuanOperateService;
    @Scheduled(cron = "0/10 * * * * ? ")
    @SneakyThrows
    public void toOut(){
        long start  = new Date().getTime();
        log.info("------------------------------------------开始出餐------------------------------------------------------------");
        String time = DateUtils.getTime();
        List<Order> list = orderService.getList(new Search().add("orderSource","ELEME").add("outStatus", SearchTypeEnum.EqualTo, "READY").add("serverId",SearchTypeEnum.EqualTo,pythonServerConfig.getServerId()).add("theoryOutTime",SearchTypeEnum.LessThanOrEqual,time));
        list.forEach(order -> {

            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
                    query.setOrderId(order.getId());
                    Store store = storeService.get(order.getStoreId());
                    query.setStoreId(store.getId());
                    try {
                        Long pStoreId = store.getPStoreId();
                        if(pStoreId != null){
                            Store pStore = storeService.get(pStoreId);
                            query.setKsid(pStore.getCookie());
                        }else{
                            if(!store.getOnlineStatus().equals("ONLINE")){
                                return;
                            }
                            query.setKsid(store.getCookie());
                        }
                        Boolean result = redisTemplate.opsForValue().setIfAbsent("out:" + order.getId(), "1", 60, TimeUnit.SECONDS);
                        if(!result){
                            return;
                        }
                        ElmeOperateServiceImpl.OutResult outResult = elmeOperateService.excuteOutFood(query);
                        redisTemplate.opsForValue().set("outstatus:"+order.getOutTradeNo(),"OUTED",4,TimeUnit.HOURS);
                    } catch (Exception e) {
                        log.info(e.getMessage(),e);
                        order.setOutStatus("EXCEPT");
                        orderService.update(order.getId(),order,"task");
                    }
                }
            });

        });
        long end  = new Date().getTime();
        log.info("------------------------------------------出餐结束共耗时{}ms------------------------------------------------------------",end-start);
    }



    @Resource
    PythonServerConfig pythonServerConfig;


    @PostConstruct
    @Scheduled(cron = "0 9 */1 * * ?")
    public void auth(){

        long start  = new Date().getTime();
        log.info("------------------------------------------开始出餐------------------------------------------------------------");
        String time = DateUtils.getTime();
        List<Store> list = storeService.getList(new Search().add("storeStatus", SearchTypeEnum.EqualTo,"1").add("platform","ELEME").add("serverId",SearchTypeEnum.EqualTo,pythonServerConfig.getServerId()).add("onlineStatus",SearchTypeEnum.EqualTo,"ONLINE"));
        list.forEach(store ->{
            ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
            query.setShopId(store.getRegionId());
            query.setKsid(store.getCookie());
            query.setStoreId(store.getId());
            elmeOperateService.getAccessToken(query);
        });
    }

//    @PostConstruct
//    public void setOff(){
//        log.info("开始将所有饿了么门店设置为离线状态");
//        List<Store> storeList = storeService.getList(new Search().add("serverId",SearchTypeEnum.EqualTo,pythonServerConfig.getServerId()).add("storeStatus", SearchTypeEnum.EqualTo,"1").add("platform","ELEME").add("onlineStatus",SearchTypeEnum.EqualTo,"ONLINE"));
//        storeList.forEach(store -> {
//            store.setOnlineStatus("OFF");
//            storeService.update(store.getId(),store,"task");
//            meiTuanOperateService.downNotice(store.getId());
//        });
//    }

//    public void activeWebdriver(){
//        log.info("开始打开激活中的浏览器");
//        List<Store> storeList = storeService.getList(new Search().add("serverId",SearchTypeEnum.EqualTo,pythonServerConfig.getServerId()).add("storeStatus", SearchTypeEnum.EqualTo,"1").add("platform","ELEME").add("onlineStatus",SearchTypeEnum.EqualTo,"ONLINE"));
//        storeList.forEach(store -> {
//            try {
//                reOpen(store.getId());
//            } catch (Exception e) {
//                System.out.println(store.getStoreName()+"重新登录失败");
//            }
//        });
//    }


//    public void reOpen(Long storeId){
//        SeleniumServiceImpl seleniumService = new SeleniumServiceImpl();
//        Store store = storeService.get(storeId);
//        WebDriver webDriver = seleniumService.getWebDriver();
//        webDriver.get("https://melody.shop.ele.me/login");
//        String elemcookie = store.getElemcookie();
//        List<Cookie> cookies = JSON.parseArray(elemcookie, Cookie.class);
//        cookies.forEach(cookie -> {
//            try {
//                webDriver.manage().addCookie(cookie);
//            } catch (Exception e) {
//                log.info(e);
//            }
//        });
//        String elemstorage = store.getElemstorage();
//        Map map = JSON.parseObject(elemstorage, Map.class);
//        JavascriptExecutor js = (JavascriptExecutor) webDriver;
//        for (Object o : map.keySet()) {
//            String script = "window.localStorage.setItem('"+o+"','"+map.get(o)+"')";
//            js.executeScript(script);
//
//        }
//
//        webDriver.get("https://melody.shop.ele.me/app/shop/"+store.getRegionId()+"/order__processing#app.shop.order.processing");
//        webDriver.switchTo().frame("app_shop_order_processing");
//        webDriver.close();
//        seleniumService.webDriverMap.put(store.getRegionId(),webDriver);
//        System.out.println(store.getStoreName()+"登录成功");
//    }



}
